package com.automobile.backstage.Realms;

import com.automobile.backstage.domain.User;
import com.automobile.backstage.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 类的作用
 *
 * @author liujiamiao
 * @email 2544296058@qq.com
 * @date 2020-03-11 22:36
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        UsernamePasswordToken currentUser = (UsernamePasswordToken) token;

        User user = null;
        try {
            user = userService.findUserByUser(currentUser.getUsername());
        } catch (Exception e) {
            e.printStackTrace();
        }

        if(user==null){
            throw new UnknownAccountException("The user does not exist.");
        }

        if(user.getStatus().equals("N")){
            throw new LockedAccountException("Account locked");
        }

        ByteSource salt = ByteSource.Util.bytes(user.getPhone());

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(), salt, getName());

        return info;
    }
}
